package com.qfedu.entity.chapter2.course12;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class AESTest {

    public static void main(String[] args) {
        String password = "passwordpassword";
        String content = "学习算法，有益身心健康!！";
        byte[] encryptResult = encrypt(password, content);
        byte[] decryptResult = decrypt(password, encryptResult);
        //加密后字节数组转成16进制字符串
        String encryptStr = parseByte2HexStr(encryptResult);
        printMsg("========\n加密前:%s\n加密后:%s\n解密后：%s", content, encryptStr, new String(decryptResult));

        //采用AES/ECB/NoPadding时，要求密钥长度16、24、32中的一个、待加密内容的byte[]长度必须是16的倍数
        encryptResult = encrypt2(password, content);
        decryptResult = decrypt2(password, encryptResult);
        encryptStr = parseByte2HexStr(encryptResult);
        printMsg("========\n加密前:%s\n加密后:%s\n解密后：%s", content, encryptStr, new String(decryptResult));
    }

    private static void printMsg(String template, Object... args) {
        System.out.println(String.format(template, args));
    }


    /**
     * 加密
     *
     * @param content 需要加密的内容
     * @return
     */
    public static byte[] encrypt(String password, String content) {
        try {
//            KeyGenerator keyGen = KeyGenerator.getInstance("AES");
//            keyGen.init(256, new SecureRandom(password.getBytes()));
//            SecretKeySpec key = new SecretKeySpec(keyGen.generateKey().getEncoded(), "AES");
            SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return cipher.doFinal(byteContent);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("AES加密失败" + e.getMessage());
        }
        return null;
    }

    public static byte[] decrypt(String password, byte[] content) {
        try {
//            KeyGenerator keyGen = KeyGenerator.getInstance("AES");
//            keyGen.init(256, new SecureRandom(password.getBytes()));
//            SecretKeySpec key = new SecretKeySpec(keyGen.generateKey().getEncoded(), "AES");
            SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            return cipher.doFinal(content);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("AES解密失败" + e.getMessage());
        }
        return null;
    }

    /**
     * 加密
     *
     * @param content 需要加密的内容
     * @return
     */
    public static byte[] encrypt2(String password, String content) {
        try {
            byte[] bytePassword = password.getBytes();
//            bytePassword = checkByteLength(bytePassword);
            SecretKeySpec key = new SecretKeySpec(bytePassword, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
            byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
//            byteContent = checkByteLength(byteContent);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return cipher.doFinal(bytePassword);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("AES加密失败" + e.getMessage());
        }
        return null;
    }

    public static byte[] decrypt2(String password, byte[] content) {
        try {
            byte[] bytePassword = password.getBytes();
//            bytePassword = checkByteLength(bytePassword);
            SecretKeySpec key = new SecretKeySpec(bytePassword, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, key);
            return cipher.doFinal(content);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("AES解密失败" + e.getMessage());
        }
        return null;
    }

    private static byte[] checkByteLength(byte[] byteContent) {
        int length = byteContent.length;
        int remainder = length % 16;
        if (remainder == 0) {
            return byteContent;
        } else {
            return Arrays.copyOf(byteContent, length + (16 - remainder));
        }
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
}
